package com.yuwen.yuwenRPC.proxy;

/**
 * @ClassNameServiceProxy
 * @Description TODO
 * @Author钰玟
 * @Date2025/3/29 下午10:23
 * @Version 1.0
 **/

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.yuwen.yuwenRPC.model.RpcRequest;
import com.yuwen.yuwenRPC.model.RpcResponse;
import com.yuwen.yuwenRPC.serializer.JdkSerializer;
import com.yuwen.yuwenRPC.serializer.Serializer;

import java.io.IOException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

/**
 * 服务代理(动态代理)
 */
public class ServiceProxy implements InvocationHandler {
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //指定序列化器
        Serializer serializer = new JdkSerializer();

        //封装请求数据
        RpcRequest rpcRequest = RpcRequest
                .builder()
                .serviceName(method.getDeclaringClass().getName()) // 服务名
                .methodName(method.getName())//方法名
                .parameterTypes(new Class[] {method.getReturnType()}) //返回参数类型
                .parameters(args)//返回参数
                .build();

        try {
            //将请求数据转化为 序列化为 rpcRequest
            byte[] bytes = serializer.serialize(rpcRequest);
            //发送请求
            /**
             * 请求地址硬编码了
             */
            try(HttpResponse httpResponse = HttpRequest.post("http://localhost:8080").body(bytes).execute()) {
                //结果字节数组
                byte[] result =httpResponse.bodyBytes();
                //封装结果字节数组 =>  反序列化
                RpcResponse rpcResponse = serializer.deserialize(result, RpcResponse.class);
                //返回数据
                return rpcResponse.getData();
            }
        } catch (IOException e) {
            e.printStackTrace();

        }
        return null;
    }
}
